/* ------------------------------------------
Script      : 「大舅哥」开发环境
Author      : DJG
Version     : 1.0
Description : 仅支持锁屏天气捷径调用
Platform    : 微信公众号「大舅哥科技」
Docs        : gitee.com/script_djg/scriptable
------------------------------------------ */

class DJG {
  constructor(arg) {
    this.arg = arg;
    this.canvas;
    this.init();
  }
  
  // 初始化
  init() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = this.arg.width;
    this.canvas.height = this.arg.height;
    this.widthScale = this.arg.width/1125;
    this.heightScale = this.arg.height/2436;
    this.fontColor = this.arg.config.fontColor || '#FFFFFF'; // 文字颜色
    this.fontShadow = this.arg.config.fontShadow || '#000000'; // 文字阴影
    this.background = eval(this.arg.config.background) || false; // 绘制背景
    this.bgColor = this.arg.config.bgColor || '#000000'; // 背景颜色
    this.bgAlpha = this.arg.config.bgAlpha || 0.1; // 背景透明
  }
  
  // 更新提醒
  isUpdate(ctx){
    try{
      const json = this.arg.version_json;
      if(json.version != json.lineVersion){
        let text = "💥发现新版本！";
        this.setTextStyle(ctx, 30, "Arial-BoldMT");
        this.fillText(ctx, text, 562, 2360);
      }
    }catch(e){};
  }
  
  // 文本样式
  setTextStyle(ctx, fontSize, font, align, color){
	ctx.textAlign = align || "center";
    ctx.font = (fontSize*this.widthScale)+'px '+font;
	ctx.fillStyle = color || this.fontColor;
  }
  
  fillText(ctx, text, x, y){
    x = x*this.widthScale, y = y*this.heightScale
    ctx.fillText(text, x, y);
  }
  
  // 文本阴影
  setTextShadow(ctx, offsetX, offsetY, alpha=0.3, blur, color){
    ctx.shadowColor = this.set16ToRgb(color||this.fontShadow, alpha);
	ctx.shadowBlur = blur || 10;
	ctx.shadowOffsetY = offsetY || 5;
	ctx.shadowOffsetX = offsetX || 5;
  }
  
  //将16进制的转换为rgba
  set16ToRgb(str, alpha=1){
    var reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
    if(!reg.test(str)){return;}
    let newStr = (str.toLowerCase()).replace(/\#/g,'')
    let len = newStr.length;
    if(len == 3){
      let t = ''
      for(var i=0;i<len;i++){
        t += newStr.slice(i,i+1).concat(newStr.slice(i,i+1))
      }
      newStr = t
    }
    let arr = []; //将字符串分隔，两个两个的分隔
    for(var i =0;i<6;i=i+2){
      let s = newStr.slice(i,i+2)
      arr.push(parseInt("0x" + s))
    }
    return 'rgba('+arr.join(",")+','+alpha+')';
  }
  
  // 获取canvas画布
  getCanvas(){
    return this.canvas;
  }
  
  // 获取Activity对象
  getContext(){
    return this.canvas.getContext("2d");
  }
  
  // 清除画布
  clearRect(ctx, x, y, w, h){
    x = x*this.widthScale, y = y*this.heightScale;
    w = w*this.widthScale, h = h*this.heightScale;
    ctx.clearRect(x, y, w, h);
  }
  
  // 画线的方法
  drawLine(ctx, x, y, endX, endY, alpha=1, color=this.fontColor){
    x = x*this.widthScale, y = y*this.heightScale;
    endX = endX*this.widthScale, endY = endY*this.heightScale;
    ctx.strokeStyle = this.set16ToRgb(color, alpha);;
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    ctx.closePath();
  }
  
  // 绘制图形
  drawGraphics = {
    // 圆形
    round: (ctx, x, y, r, type, alpha, color=this.fontColor, start = 0, end = 360) => {
      x = x*this.widthScale, y = y*this.heightScale, r = r*this.widthScale;
      var unit = Math.PI / 180;
      ctx.beginPath();
      ctx.arc(x, y, r, start * unit, end * unit);
      ctx[type + 'Style'] = this.set16ToRgb(color, alpha);
      ctx.closePath();
      
      ctx[type]();
    },
    // 圆角矩形
    roundRect: (ctx, x, y, w, h, r, bgColor, alpha, lineColor) => {
      x = x*this.widthScale, y = y*this.heightScale, r = r*this.widthScale;
      w = w*this.widthScale, h = h*this.heightScale;
      if(w < 2*r) r = w / 2;
      if(h < 2*r) r = h / 2;
      ctx.beginPath();
      ctx.moveTo(x+r, y);
      ctx.arcTo(x+w, y, x+w, y+h, r);
      ctx.arcTo(x+w, y+h, x, y+h, r);
      ctx.arcTo(x, y+h, x, y, r);
      ctx.arcTo(x, y, x+w, y, r);
      ctx.fillStyle = this.set16ToRgb(bgColor, alpha);
      ctx.fill();
      if(lineColor)ctx.stroke();
      ctx.closePath();
    }
  }
  
  // 绘制圆形
  drawRound (ctx, x, y, r, type, alpha, color=this.fontColor, start = 0, end = 360) {
    x = x*this.widthScale, y = y*this.heightScale, r = r*this.widthScale;
    var unit = Math.PI / 180;
    ctx.beginPath();
    ctx.arc(x, y, r, start * unit, end * unit);
    ctx[type + 'Style'] = this.set16ToRgb(color, alpha);
    ctx.closePath();
    ctx[type]();
  }
  
  // 绘制圆角矩形
  drawRoundRect (ctx, x, y, w, h, r, type, alpha=1, color=this.fontColor) {
    x = x*this.widthScale, y = y*this.heightScale, r = r*this.widthScale;
    w = w*this.widthScale, h = h*this.heightScale;
    if(w < 2*r) r = w / 2;
    if(h < 2*r) r = h / 2;
    ctx.beginPath();
    ctx.moveTo(x+r, y);
    ctx.arcTo(x+w, y, x+w, y+h, r);
    ctx.arcTo(x+w, y+h, x, y+h, r);
    ctx.arcTo(x, y+h, x, y, r);
    ctx.arcTo(x, y, x+w, y, r);
    ctx[type + 'Style'] = this.set16ToRgb(color, alpha);
    ctx.closePath();
    ctx[type]();
  }
  
  // 匹配地址
  getAddress (location, match = '区') {
    const matchs = ['省','壮族自治区','回族自治区','自治州','维吾尔自治区','自治区','市','区','县','镇','路'];
    let index = matchs.findIndex(item =>{
      return item == match
    })
    let regStr = '';
    for(let i = 0; i < index+1; i++){
      regStr = i === 0 ? matchs[i] : regStr+'|'+matchs[i];
    };
    let address = null;
    let citys = location.split(' ');
    index = citys.findIndex(item =>{
      return item.indexOf(match) != -1;
    });
    if(index!=-1)citys = citys.splice(0, index+1);
    let reg = RegExp(eval('/'+regStr+'/g'));
    citys.forEach(function (item, index) {
      const str = citys[index].match(reg);
      if (str){
        address = citys[index];
      }
    })
    return address;
  }
  
  // 格式化时间
  dateFormat(fmt = 'yyyy年MM月d日 EEE', date = new Date()) {
    let ret;
    let opt = {
      "y+": date.getFullYear().toString(),        // 年
      "M+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "h+": date.getHours().toString(),           // 时
      "m+": date.getMinutes().toString(),         // 分
      "s+": date.getSeconds().toString()          // 秒
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt=fmt.replace(ret[1],(ret[1].length==1)?(opt[k]):(opt[k].padStart(ret[1].length,"0")))
      }
    }
    return fmt;
  }
}

const Runing = (W) => {
  let canvas = W.getCanvas();
  let context = W.getContext();
  W.drawing(context);
  W.isUpdate(context);
  document.write(canvas.toDataURL().split(',')[1]);
}